package com.qfedu.filter;

import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import com.qfedu.service.impl.UserServiceImpl;
import com.qfedu.utils.Base64Utils;
import com.qfedu.utils.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.SQLException;

@WebFilter("/login.jsp")
public class LoginFilter implements Filter {
    private UserService userService = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        userService = new UserServiceImpl();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            //有自动登陆对应 cookie
            if (Constants.AUTO_NAME.equals(cookie.getName())){
                //进行解码组合的用户名和密码  再用split分割 得到单独的用户名和密码
                String usernameAndPassword = Base64Utils.decode(cookie.getValue());
                String[] strings = usernameAndPassword.split(Constants.FLAG);
                String username = strings[0];
                String password = strings[1];
                try {
                    User user = userService.findUserByUserName(username);
                    //判断密码是否正确，成功就跳转到首页
                    if (user.getUpassword().equals(password)){
                        request.getSession().setAttribute("loginUser",user);
                        request.getRequestDispatcher("/index.jsp").forward(request,servletResponse);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        //放行 通过
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
